package com.ybwh.springboot1.conf.intercepter;

import com.alibaba.fastjson.JSON;
import com.ybwh.springboot1.annotation.LoginRequired;
import com.ybwh.springboot1.common.RespData;
import com.ybwh.springboot1.util.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>
 * 判断登录状态
 * </p>
 *
 * @author fanbeibei
 * @version V1.0
 * @since 2019/5/16 23:01
 */
@Slf4j
public class LoginRequiredInterceptor implements HandlerInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		HandlerMethod handlerMethod = (HandlerMethod) handler;
		LoginRequired loginRequired = handlerMethod.getMethod().getAnnotation(LoginRequired.class);
		if (null == loginRequired) {
			loginRequired = handlerMethod.getBeanType().getAnnotation(LoginRequired.class);
		}

		if (null == loginRequired) {
			return true;
		}

		String token = TokenUtil.getToken(request);
		if (null == token || TokenUtil.isExpired(token)) {

			if (isAjax(handlerMethod)) {
				try {
					response.setContentType("application/json;charset=utf-8");
					response.getWriter().print(JSON.toJSONString(RespData.reLoginResp("请重新登录")));
				} catch (IOException e) {
					log.error(e.getMessage(), e);
				}
			} else {
				response.sendRedirect("login");
			}

			return false;
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {

	}

	/**
	 * 是否是ajax请求
	 *
	 * @param handlerMethod
	 * @return
	 */
	private boolean isAjax(HandlerMethod handlerMethod) {
		ResponseBody responseBody = handlerMethod.getMethodAnnotation(ResponseBody.class);
		if (null != responseBody) {
			return true;
		}

		RestController restController = handlerMethod.getBeanType().getAnnotation(RestController.class);
		if (null != restController) {
			return true;
		}

		return false;
	}



}
